package com.qfedu.index.addrshow.service.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import com.qfedu.index.addrshow.service.beans.City;
import com.qfedu.index.addrshow.service.dao.CityDAO;
import com.qfedu.index.addrshow.service.service.CityService;
import com.qfedu.util.JsonTools;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

@Service
public class CityServiceImpl implements CityService {

    @Resource
    private CityDAO cityDAO;

    @Resource
    private StringRedisTemplate st;

    @Override
    public List<City> getCity(Integer parentid) {
        List<City> city = cityDAO.getCity(parentid);
        return city;
    }

    @Override
    public List<City> getOne() throws IOException {
//        ObjectMapper objectMapper = new ObjectMapper();
        String types = st.boundValueOps("cityes").get();
        System.out.println(types);
        //如果查到的数据不存在，则查询数据库
        if(types == null){
            List<City> list = cityDAO.getOne();
            System.out.println(list);
            String s = JsonTools.obj2String(list);
            //将数组转换成字符串 便于存储到redis
//            String s = objectMapper.writeValueAsString(list);
            //存储到redis
            st.boundValueOps("cityes").set(s);
            return list;
            //如果查到的数据存在，则直接查redis
        }else {
//            List list = objectMapper.readValue(types, new TypeReference<List<City>>(){});
            List<City> list = JsonTools.string2Collection(types, List.class, City.class);
            return list;
        }
    }
}
